<?php

namespace App\Services;

use App\Common\Libs\Ali\Oss;
use App\Common\Libs\ArrayHelper;
use App\Common\Libs\IdBuilder;
use App\Common\Libs\Json;
use App\Consts\GlobalReportConst;
use App\Consts\GlobalUploadConst;
use App\Exceptions\Error;
use Illuminate\Support\Facades\DB;

class TortService extends BaseService
{

    private $_repository;

    public function __construct()
    {
        parent::__construct();
        $this->_repository = repository()->TortRepository;
    }

    /**
     * @title 新增举报
     * @param array $params
     * @return bool|\Illuminate\Http\JsonResponse
     */
    public function addTort($params)
    {
        $params = ArrayHelper::merge($params, [
            'tort_id' => IdBuilder::getUniqueID()
        ]);

        // 事务级保存逻辑
        DB::beginTransaction();
        try {
            // 新增举报
            $params['category_id'] = GlobalReportConst::CATEGORY_TYPE_TORT;
            $report = service()->ReportService->addReport($params);
            if (!$report) {
                return $this->throwError($report);
            }
            $params['report_id'] = $report->id;
            $tort = $this->_repository->create($params);
            if (!$tort) {
                return $this->throwError($tort);
            }
            if (!empty($params['file'])) {
                $annexUrlArr = $this->_uploadAnnex($params['user_id']);
                if (!$annexUrlArr) {
                    return Error::handle(lang('Upload file fail'));
                }
                $this->_repository->createAnnex([
                    'tort_id' => $params['tort_id'],
                    'url' => Json::encode($annexUrlArr),
                ]);
            }
            DB::commit();
            return true;
        } catch (\Exception $e) {
            DB::rollBack();
            return Error::throw($e);
        }
    }

    /**
     * 获取防侵权类型
     * @return array
     */
    public function getType()
    {
        return GlobalReportConst::TORT_TYPE_LIST;
    }

    /**
     * 上传附件
     * @param $userId
     * @return array|bool
     */
    private function _uploadAnnex($userId)
    {
        $annexUrl = Oss::getInstance(GlobalUploadConst::OBJECT_TORT_ANNEX)
            ->batchUploadClientFileByBase64($userId);
        if (!$annexUrl) {
            return false;
        }
        return ArrayHelper::getColumn($annexUrl, 'url');
    }

}
